﻿using System;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using DemoApp1.Models;
using System.Web.Security;
using Newtonsoft.Json.Linq;
using DemoApp1.Common;
using DemoApp1.Attribute;

namespace DemoApp1.Controllers
{
    //[CustomAuthorize(ischeck = false)]
    public class AccountController : BaseController
    {
        public ActionResult Login()
        {
            string returnUrl = null;
            var urlReferrer = HttpContext.Request.UrlReferrer;
            if (urlReferrer != null)
            {
                returnUrl = urlReferrer.ToString();
            }
            else
            {
                returnUrl = "/";
            }

            var cookie = new HttpCookie(AppConfig.ClientReturnUrlCookieName, returnUrl);
            System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
            string authorizationServerAddress = string.Format("{0}{1}?client_id={2}&redirect_uri={3}&response_type={4}", AppConfig.AuthorizationServerBaseAddress, AppConfig.AuthorizePath, AppConfig.ClientId, AppConfig.RedirectUri, AppConfig.ResponseType);
            return Redirect(authorizationServerAddress);
        }

        /// <summary>
        /// After login from OAuth Server, will be redirected to here
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public ActionResult LoginRedirect(string code)
        {
            // Get AccessToken
            RestClientHelp restClientHelp = new RestClientHelp(AppConfig.AuthorizationServerBaseAddress, AppConfig.TokenPath);
            string accessTokenReuslt = restClientHelp.AccessToken(AppConfig.ClientId, AppConfig.ClientSecret, code);

            string returnUrl = "/";

            //HttpCookie ClientReturnUrlCookie = HttpContext.Request.Cookies[AppConfig.ClientReturnUrlCookieName];
            //if (ClientReturnUrlCookie != null)
            //{
            //    // Remove return URL cookie
            //    ClientReturnUrlCookie.Expires = DateTime.Now.AddDays(-1);
            //    HttpContext.Response.Cookies.Add(ClientReturnUrlCookie);

            //    returnUrl = !string.IsNullOrEmpty(ClientReturnUrlCookie.Value) ? ClientReturnUrlCookie.Value : "/";
            //}
            //else
            //{
            //    returnUrl = "/";
            //}

            if (!string.IsNullOrEmpty(accessTokenReuslt))
            {
                dynamic contentForAccessToken = JObject.Parse(accessTokenReuslt);
                string accessToken = contentForAccessToken.access_token;
                var userdata = restClientHelp.GetUserData(accessToken);
                //string refreshToken = contentForAccessToken.refresh_token;

                //// Get Refreshed AccessToken by RefreshToken, for subsequent Ajax request
                //string refreshTokenResult = restClientHelp.RefreshToken(AppConfig.ClientId, AppConfig.ClientSecret, refreshToken);

                //if (!string.IsNullOrEmpty(refreshTokenResult))
                //{
                //    dynamic contentForRefreshToken = JObject.Parse(refreshTokenResult);
                //    string refreshedAccessToken = contentForRefreshToken.access_token;

                //    // Set Refreshed AccessToken Cookie
                //    var refreshedAccessTokenTicket = new FormsAuthenticationTicket(1, "UserName", DateTime.Now, DateTime.Now, false, refreshedAccessToken);
                //    var encryptedRefreshedAccessTokenTicket = FormsAuthentication.Encrypt(refreshedAccessTokenTicket);
                //    var refreshedAccessTokenCookie = new HttpCookie(AppConfig.RefreshedAccessTokenCookieName, encryptedRefreshedAccessTokenTicket);
                //    refreshedAccessTokenCookie.HttpOnly = true;
                //    System.Web.HttpContext.Current.Response.Cookies.Add(refreshedAccessTokenCookie);
                //}

                // Set AccessToken Cookie
                var accessTokenTicket = new FormsAuthenticationTicket(1, "UserName", DateTime.Now, DateTime.Now, false, accessToken);
                var encryptedAccessTokenTicket = FormsAuthentication.Encrypt(accessTokenTicket);
                var accessTokenCookie = new HttpCookie(AppConfig.AccessTokenCookieName, encryptedAccessTokenTicket);
                accessTokenCookie.HttpOnly = true;
                System.Web.HttpContext.Current.Response.Cookies.Add(accessTokenCookie);

               

                // Redirect to the 'ReturnUrl' Page
                return Redirect(returnUrl);
            }

            return Redirect(returnUrl);
        }

        public ActionResult Logout()
        {
            string returnUrl = null;

            var urlReferrer = HttpContext.Request.UrlReferrer;
            if (urlReferrer != null)
            {
                returnUrl = HttpContext.Request.UrlReferrer.ToString();
            }
            else
            {
                returnUrl = "/";
            }

            Session.Clear();
            Session.Abandon();
            FormsAuthentication.SignOut();
            var cookie = Response.Cookies[FormsAuthentication.FormsCookieName];
            if (cookie != null)
            {
                cookie.Expires = new DateTime();
            }
            HttpContext.Response.Cookies.Clear();
            Response.Cookies.Add(cookie);

            // After Logout, remove RefreshedAccessToken Cookie
            HttpCookie refreshedAccessTokenCookie = HttpContext.Request.Cookies[AppConfig.RefreshedAccessTokenCookieName];
            if (refreshedAccessTokenCookie != null)
            {
                refreshedAccessTokenCookie.Expires = DateTime.Now.AddDays(-1);
                HttpContext.Response.Cookies.Add(refreshedAccessTokenCookie);
            }

            HttpCookie accesstoken = HttpContext.Request.Cookies[AppConfig.AccessTokenCookieName];
            if (accesstoken != null)
            {
                accesstoken.Expires = DateTime.Now.AddDays(-1);
                HttpContext.Response.Cookies.Add(accesstoken);
            }



            //Redirect to OAuth Server's logout action
            return Redirect(string.Format("{0}{1}?ReturnUrl={2}", AppConfig.AuthorizationServerBaseAddress, AppConfig.LogoutPath, returnUrl));
        }

    }
}